package org.github.project.chain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import java.util.List;

/**
 * 订单处理责任链配置
 *
 * @auther yang
 * @date 2022/1/21 11:08
 */
@Component
public class OrderHandlerChain {

    private AbstractHandler chain;

    /**
     * <ol>
     *     <li>自动注入会遵守 @Order 和 @Priority 标注组件的加载顺序。</li>
     *     <li>从 ApplicationContext 中获取 Bean 顺序会乱</li>
     * </ol>
     *
     * @see Order
     * @see Priority
     * @see ApplicationContext
     */
    @Autowired
    private List<AbstractHandler> handlers;

    @PostConstruct
    public void initChain() {
        this.chain = this.handlers.get(0);
        for (int i = 1; i < this.handlers.size(); i++) {
            AbstractHandler currentHandler = this.handlers.get(i - 1);
            AbstractHandler nextHandler = this.handlers.get(i);
            currentHandler.setNextHandler(nextHandler);
        }
    }

    public AbstractHandler getChain() {
        return chain;
    }


    /**
     * 参数校验处理
     */
    @Component
    @Priority(1)   // 顺序排第一, 优先校验
    public static class CheckParamHandler extends AbstractHandler {

        @Override
        protected void doHandle(Object request, Object response) {
            System.out.println("非空参数检查");
        }
    }

    /**
     * 安全调用处理
     */
    @Component
    @Priority(2)
    public static class checkSecurityHandler extends AbstractHandler {

        @Override
        protected void doHandle(Object request, Object response) {
            System.out.println("安全调用检查");
        }
    }

    /**
     * 黑名单检查
     */
    @Component
    @Priority(3)
    public static class checkBlackListHandler extends AbstractHandler {

        @Override
        protected void doHandle(Object request, Object response) {
            System.out.println("黑名单校验");
        }
    }

    /**
     * 检查规则
     */
    @Component
    @Priority(4)
    public static class CheckRuleHandler extends AbstractHandler {

        @Override
        protected void doHandle(Object request, Object response) {
            System.out.println("检查规则");
        }
    }


}
